package lxs.tool.liberator.work.service.imp;

import lxs.tool.liberator.common.base.result.Response;

import lxs.tool.liberator.common.utils.IDCreator;
import lxs.tool.liberator.work.mapper.EntityMapper;
import lxs.tool.liberator.work.mapper.FieldMapper;
import lxs.tool.liberator.work.mapper.ProjectMapper;
import lxs.tool.liberator.work.param.out.EntityOut;
import lxs.tool.liberator.work.pojo.Entity;
import lxs.tool.liberator.work.pojo.Field;
import lxs.tool.liberator.work.pojo.Project;
import lxs.tool.liberator.work.service.EntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Service("EntityServiceImp")
public class EntityServiceImp implements EntityService {
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private FieldMapper fieldMapper;

    @Override
    public Response showTable() {
        Project mainProject = projectMapper.getMainProject();
        List<EntityOut> entityOuts = entityMapper.showTable(mainProject.getId());
        List<List<EntityOut>> lists = new ArrayList<>();
        List<EntityOut> row = new ArrayList<>();
        int i = 3;
        boolean flag = true;
        for (int j = 0; j < entityOuts.size(); j++) {
            List<Field> list = fieldMapper.getByEId(entityOuts.get(j).getId());
            entityOuts.get(j).setFieldList(list);
            row.add(entityOuts.get(j));
            i--;
            if (flag && i == 1) {
                i = 0;
                flag = false;
            }
            if (i == 0) {
                lists.add(row);
                row = new ArrayList<>();
                i = 3;
            }else {
                if(j==entityOuts.size()-1){
                    lists.add(row);
                }
            }
        }
        return Response.send(lists);
    }

    @Override
    public Response getOptions() {
        Project mainProject = projectMapper.getMainProject();
        return Response.send(entityMapper.getOptions(mainProject.getId()));
    }

    @Override
    public Response add() {
        String s = IDCreator.get("entity");
        Project mainProject = projectMapper.getMainProject();
        Entity entity = new Entity();
        entity.setId(s);
        entity.setProjectId(mainProject.getId());
        entityMapper.insert(entity);
        return Response.send(s);
    }

    @Override
    public Response deleteById(String id) {
        entityMapper.deleteById(id);
        fieldMapper.deleteByEntityId(id);
        return Response.success();
    }

    @Override
    public Response update(Entity entity) {
        Entity entity1 = entityMapper.selectById(entity.getId());
        entityMapper.updateById(entity.setProjectId(entity1.getProjectId()));
        return Response.success();
    }
}
